# coding=utf-8
from PIL import Image, ImageChops
import shutil
import os
from config import DATA_PATH, NGINX_HOST
import random
import string

ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg'])


class Graphics:
	data_path = DATA_PATH
	nginx_host = NGINX_HOST

	@classmethod
	def fixed_size(cls, infile, outfile, width, height):
		"""按照固定尺寸处理图片"""
		im = Image.open(infile)
		out = im.resize((width, height), Image.ANTIALIAS)
		out.save(outfile)

	@classmethod
	def resize_by_width(cls, infile, outfile, w_divide_h):
		"""按照宽度进行所需比例缩放"""
		im = Image.open(infile)
		(x, y) = im.size
		x_s = x
		y_s = x // w_divide_h
		out = im.resize((x_s, y_s), Image.ANTIALIAS)
		out.save(outfile)

	@classmethod
	def resize_by_height(cls, infile, outfile, w_divide_h):
		"""按照高度进行所需比例缩放"""
		im = Image.open(infile)
		(x, y) = im.size
		x_s = y * w_divide_h
		y_s = y
		out = im.resize((x_s, y_s), Image.ANTIALIAS)
		out.save(outfile)

	@classmethod
	def resize_by_size(cls, infile, outfile, size):
		"""按照生成图片文件大小进行处理(单位KB)"""
		size *= 1024
		im = Image.open(infile)
		size_tmp = os.path.getsize(infile)
		q = 100
		while size_tmp > size and q > 0:
			out = im.resize(im.size, Image.ANTIALIAS)
			out.save(outfile, quality=q)
			size_tmp = os.path.getsize(outfile)
			q -= 5
		if q == 100:
			shutil.copy(infile, outfile)

	@classmethod
	def cut_by_ratio(cls, infile, outfile, width, height):
		"""按照图片长宽比进行分割"""
		im = Image.open(infile)
		width = float(width)
		height = float(height)
		(x, y) = im.size
		if width > height:
			region = (0, int((y - (y * (height // width))) // 2), x, int((y + (y * (height // width))) / 2))
		elif width < height:
			region = (int((x - (x * (width // height))) // 2), 0, int((x + (x * (width // height))) / 2), y)
		else:
			region = (0, 0, x, y)

		# 裁切图片
		crop_img = im.crop(region)
		# 保存裁切后的图片
		crop_img.save(outfile)

	@classmethod
	def format_filename(cls, file_data_path, new_file_name):
		file_type = file_data_path.rsplit('.', 1)[1]
		return ".".join([new_file_name + "_small", file_type])

	@classmethod
	def format_data_small_url(cls, file_data_path):
		new_file_path = file_data_path.rsplit('/', 1)[0]
		file_name = file_data_path.rsplit('.', 1)[0]
		file_type = file_data_path.rsplit('.', 1)[1]
		return "/".join([new_file_path, ".".join([file_name + "_small", file_type])])

	@classmethod
	def format_data_nginx_url(cls, file_data_path):
		"""本地存储转换成nginx渲染地址"""
		return file_data_path.replace(cls.data_path, cls.nginx_host)

	@classmethod
	def format_nginx_data_url(cls, nginx_file_path):
		"""nginx渲染地址转换成本地存储"""
		return nginx_file_path.replace(cls.nginx_host, cls.data_path)

	@classmethod
	def mkdir_file_data_path(cls, file_data_path):
		"""判断目录是否存在,不存在则创建"""
		new_file_path = file_data_path.rsplit('/', 1)[0]
		if os.path.exists(new_file_path):
			pass
		else:
			os.makedirs(new_file_path)

	@classmethod
	def remove_data_file(cls, db_path_url):
		# file_data_path = "/".join([cls.data_path, db_path_url.split("/")[0]])
		# shutil.rmtree(db_path_url.split("/")[0])

		file_data_path = "/".join([cls.data_path, db_path_url])
		cls._remove_data_file(file_data_path)

	@classmethod
	def _remove_data_file(cls, temp_file_data_path):
		if (os.path.exists(temp_file_data_path)):
			os.remove(temp_file_data_path)

	@classmethod
	def allowed_file(cls, filename):
		return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

	@classmethod
	def bg_merge(cls, bg, infile, outfile):
		temp_path = ''.join(random.sample(string.ascii_letters + string.digits, 8))
		temp_path_png = '.'.join([temp_path, 'png'])
		temp_file_data_path = "/".join([cls.data_path, temp_path_png])

		bg_data_path = "".join([cls.data_path, bg.rsplit('files', 1)[1]])
		print("====================bg_merge===============:", bg_data_path)
		bg_path = Image.open(bg_data_path)
		bg_path.convert('RGBA')

		if infile.startswith("http"):
			infile = cls.format_nginx_data_url(infile)
		cls.fixed_size(infile, temp_file_data_path, bg_path.size[0], bg_path.size[1])

		in_path = Image.open(temp_file_data_path)
		in_path.convert('RGBA')

		if bg_path.size == in_path.size:
			diff = ImageChops.difference(in_path, bg_path)
			diff.save(outfile)
			im = Image.open(outfile)
			x, y = im.size
			try:
				p = Image.new('RGBA', im.size, (0, 0, 0))
				p.paste(im, (0, 0, x, y), im)
				p.save(outfile)
			except:
				pass
		cls._remove_data_file(temp_file_data_path)

	@classmethod
	def image_joint(cls, file_list):
		"""
		:param file_list: [inpath, erweima, outpath]
		:return:
		"""
		a = Image.open(file_list[0])
		b = Image.open(file_list[1])

		temp_path = ''.join(random.sample(string.ascii_letters + string.digits, 8))
		temp_path_png = '.'.join([temp_path, 'png'])
		temp_file_data_path = "/".join([cls.data_path, temp_path_png])

		new_img = Image.new('RGB', (a.size[0], b.size[1] + a.size[1]), 255)

		if a.size[0] != b.size[0]:
			cls.fixed_size(file_list[1], temp_file_data_path, a.size[0], b.size[1])
			c = Image.open(temp_file_data_path)
		else:
			c = b
		x = y = 0

		_image_list = [a, c]
		for img in _image_list:
			new_img.paste(img, (x, y))
			y += a.size[1]

		new_img.save(file_list[2])
		cls._remove_data_file(temp_file_data_path)
